package Main;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class AddCarGoods {
	String url = "jdbc:mysql://localhost:3306/goods";
    String userName = "root";
    String password = "kamisama";
    String driverName = "com.mysql.jdbc.Driver";
    String strSql1 = "insert into cars(name,price,num,description) select name,price,num,description from good where id = ?";
    String strSql2 = "updates cars et sum=num*price where id = ?";
    Connection con1 = null;
	java.sql.PreparedStatement pstmt1 = null;
	java.sql.PreparedStatement pstmt2 = null;
	ResultSet rs = null;
	String driverName1 = "com.mysql.jdbc.Driver";
    Scanner sc = new Scanner(System.in);
	public void Addcargoods(int i){
	    try {
	        Class.forName(driverName);// jdbc4.0 后无需使用这句进行驱动注册操作
	        con1 =DriverManager.getConnection(url, userName, password); // 根据参数的插入数据
	        pstmt1 = con1.prepareStatement(strSql1);
	        	pstmt1.setInt(1, i);
	        pstmt2 = con1.prepareStatement(strSql2);
	        	pstmt2.setInt(1, i);
		        pstmt1.executeUpdate();
		        pstmt2.executeUpdate();
	    } catch (SQLException e) {
	        e.printStackTrace();
	    } catch (ClassNotFoundException e) {
	        e.printStackTrace();
	    } finally {/*下面资源释放，可以使用try..with..resources语法简化*/
	        if (rs != null) {
	            try {
	                rs.close();
	                rs.close();
	            } catch (SQLException e) {
	                e.printStackTrace();
	            }
	        }
	        if (pstmt1 != null) {
	            try {
	            	pstmt1.close();
	            	pstmt1 = null;
	            } catch (SQLException e) {
	                e.printStackTrace();
	            }
	        }
	        if (con1 != null)
	            try {
	                con1.close();
	                con1 = null;
	            } catch (SQLException e) {
	                e.printStackTrace();
	            } 
	    	}
	    }
}
